// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
const TcbRouter = require('tcb-router');
cloud.init({
	env: "ws-food-8gnmfsye0135f47d"
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({
		event
	})
	const {
		ENV,
		OPENID,
		APPID
	} = cloud.getWXContext()
	app.use(async (ctx, next) => {
		ctx.wxContext = cloud.getWXContext()
		await next()
	})
	/**
	 * showdoc
	 * @catalog 云开发·数据库·新增数据
	 * @title 新增数据
	 * @description 新增数据
	 * @url models/addData 
	 */
	app.router('addData', async (ctx, next) => {
		if (!event.table || !event.data) ctx.body = false
		try {
			let res = await db.collection(event.table).add({
				data: event.data
			});
			ctx.body = res.errMsg == 'collection.add:ok' ? res._id : false;
		} catch (e) {
			console.log(e)
			ctx.body = false
		}
	})
	/**
	 * showdoc
	 * @catalog 云开发·数据库·编辑数据
	 * @title 编辑数据
	 * @description 编辑数据
	 * @url models/editData 
	 */
	app.router('editData', async (ctx, next) => {
		if (!event.table || !event.data || !event.where) ctx.body = false
		try {
			let res = await db.collection(table).where(where).update({
				data: data
			});
			ctx.body = res.errMsg == 'collection.update:ok' && res.stats.updated > 0 ? true : false;
		} catch (e) {
			ctx.body = false
		}
	})

	/**
	 * showdoc
	 * @catalog 云开发·数据库·删除数据
	 * @title 删除数据
	 * @description 删除数据
	 * @url models/delData 
	 */
	app.router('delData', async (ctx, next) => {
		if (!event.table || !event.data) ctx.body = false
		try {
			let res = await db.collection(table).where(where).remove();
			ctx.body = res.errMsg == 'collection.remove:ok' ? true : false;
		} catch (e) {
			ctx.body = false
		}
	})

	/**
	 * showdoc
	 * @catalog 云开发·数据库·获取数据
	 * @title 获取数据
	 * @description 获取数据
	 * @url models/getData 
	 */
	app.router('getData', async (ctx, next) => {
		if (!event.table) ctx.body = []
		try {
			let Db = await db.collection(event.table)
			if (typeof event.orderBy != 'undefined') {
				Db = await Db.orderBy(event.orderBy[0], event.orderBy[1])
			}
			if (typeof event.where != "undefined") {
				Db = await Db.where(event.where)
			}
			if (typeof event.page != 'undefined') {
				Db = await Db.skip((parseInt(event.page) - 1) * parseInt(event.limit)).limit(
					parseInt(event.limit))
			}
			let res = await Db.get();
			ctx.body = res.errMsg == 'collection.get:ok' ? res.data : [];

		} catch (err) {
			ctx.body = err
		}
	})


	/**
	 * showdoc
	 * @catalog 云开发·数据库·获取多表数据
	 * @title 获取多表数据
	 * @description 获取多表数据
	 * @url models/getLookUpData 
	 */
	app.router('getLookUpData', async (ctx, next) => {
		if (!event.table) ctx.body = []
		try {
			let Db = await db.collection(event.table)
			if (typeof event.lookUp != 'undefined') {
				Db = await Db.aggregate()
					.lookup({
						from: event.lookUp.from,
						localField: event.lookUp.localField,
						foreignField: event.lookUp.foreignField,
						as: event.lookUp.as,
					})
			}
			if (typeof event.sort != 'undefined') {
				Db = await Db.sort(event.sort)
			}
			if (typeof event.match != "undefined") {
				Db = await Db.match(event.match)
			}
			if (typeof event.page != 'undefined'&&typeof event.limit != 'undefined') {
				Db = await Db.skip((parseInt(event.page) - 1) * parseInt(event.limit)).limit(parseInt(event.limit))
			}
			let res = await Db.end();
			ctx.body =  res.errMsg == 'collection.aggregate:ok' ? res.list : [];
		} catch (err) {
			ctx.body = err
		}
	})

	return app.serve();
}
